//
//  SuperviseTaskCheckVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/1/7.
//
// 【首页-检查监督】检查任务-开始检查

import Foundation
import UIKit

class SuperviseTaskCheckVC: SubLevelViewController {
    
    let taskV = SuperviseTaskCheckView()

    var id: Int64!
    
    var modal: SpRwbgModal?
    
    var param: RwKsjctjParam?

    init(id: Int64!, deptName: String?, deptId: Int64?) {
        super.init(nibName: nil, bundle: nil)
        self.id = id
        self.deptName = deptName
        self.deptId = deptId
        self.param = RwKsjctjParam(id: id)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "开始检查"
        navigationController?.navBarStyle(.white)
        view.backgroundColor = .bg
        setupUI()
        updateLoc()
        reloadData()
    }
    
    func reloadData() {
        view.showToastActivity()
        API.getJcjdKsjcrw(withParam: SpDetailParam(id: id)) { responseModel in
            DispatchQueue.main.async {
                self.view.hideToastActivity()
                self.modal = responseModel.model
                self.taskV.reload(withModal: self.modal)
            }
        }
    }
    
    func updateLoc() {
        LocManager.shared.didUpdateLocWith = { (longitude, latitude, address) -> () in
            print("Selected longitude: \(longitude) at latitude: \(latitude)")
            self.param?.lng = longitude
            self.param?.lat = latitude
            self.param?.location = address
        }
        LocManager.shared.startLoaction()
    }
    
    @objc func submitTapped() {
        let datas = self.modal?.rwjlMbs ?? []
        let mbs = taskV.rwjlMbs
        
        var rwjlMbs: [RwjlItemParam] = []
        
        if mbs.count != datas.count {
            var isMbNot = false
            for data in datas {
                let mbs = rwjlMbs.filter({ $0.id == data.id })
                isMbNot = mbs.count == 0
                if isMbNot {
//                    view.showToast(witMsg: "请完成「\(data.rwmc ?? "检查任务")」")
//                    return
                    rwjlMbs.append(RwjlItemParam(id: data.id, rwjlid: self.modal?.id, rwmbid: data.rwmbid, rwzt: "2", fjImgs: []))
                } else {
                    rwjlMbs.append(mbs[0])
                }
            }
//            return
        }

        var isNot = false
        for mb in rwjlMbs {
            if mb.rwzt == "3" && (mb.fjsm == "" || mb.fjImgs?.count == 0) {
                isNot = true
            }
        }
        if isNot == true {
            view.showToast(witMsg: "检查不通过项，请添加图片及附加说明")
            return
        }
        
        if taskV.sign1TF.img == nil || taskV.sign2TF.img == nil || taskV.sign3TF.img == nil {
            view.showToast(witMsg: "请完成签名")
            return
        }
        
        view.showToastActivity()
        
        if rwjlMbs.count == 0 {
            uploadSign1()
            return
        }
        
        var mbParam: [RwjlMbParam] = []
        
        for rwjlMb in rwjlMbs {
            if rwjlMb.fjImgs?.count == 0 {
                mbParam.append(RwjlMbParam(item: rwjlMb))
                if mbParam.count == rwjlMbs.count {
                    self.param?.rwjlMbs = mbParam
                    self.uploadSign1()
                }
            } else {
                // 上传图片
                var uploadindex = 0
                var imageUrlList: [FjdzParam] = []
                if let fjImgs = rwjlMb.fjImgs {
                    for img in fjImgs {
                        let path = FilesManager.shared.saveImage(img: img.resizedTo1MB() ?? img)
                        API.lzglUpload(withImage: path!) { responseModel in
                            if responseModel.model?.imgUrl != nil {
                                imageUrlList.append(FjdzParam(fjdz: responseModel.model!.imgUrl!))
                            }
                            uploadindex += 1
                            if rwjlMb.fjImgs!.count == uploadindex {
                                mbParam.append(RwjlMbParam(item: rwjlMb, images: imageUrlList))
                                if mbParam.count == rwjlMbs.count {
                                    self.param?.rwjlMbs = mbParam
                                    self.uploadSign1()
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    func uploadSign1() {
        var xjrqms: [FjdzParam] = []
        let path = FilesManager.shared.saveImage(img: taskV.sign1TF.img!)
        if path != nil {
            API.postStandingBookUpload(withImage: path!) { responseModel in
                xjrqms.append(FjdzParam(fjdz: responseModel.model!.imgUrl!))
                let path2 = FilesManager.shared.saveImage(img: self.taskV.sign2TF.img!)
                if path2 != nil {
                    API.postStandingBookUpload(withImage: path2!) { responseModel in
                        xjrqms.append(FjdzParam(fjdz: responseModel.model!.imgUrl!))
                        self.param?.xjrqms = xjrqms
                        self.uploadSign2()
                    }
                }
            }
        }
    }
    
    func uploadSign2() {
        let path = FilesManager.shared.saveImage(img: taskV.sign3TF.img!)
        if path != nil {
            API.postStandingBookUpload(withImage: path!) { responseModel in
                self.param?.bjrqz = responseModel.model?.imgUrl
                self.didSubmint()
            }
        }
    }
    
    func didSubmint() {
        do {
            let data: Data = try JSONEncoder().encode(param)
            let string = String(data: data, encoding: String.Encoding.utf8)
            API.postJcjdKsjctj(withParam: CommonJsonParam(jsonStr: string)) { responseModel in
                self.view.hideToastActivity()
                if responseModel.errorCode == .Success {
                    self.view.showToast(witMsg: responseModel.errorMessage)
                    NotificationCenter.default.post(name: NotiSupervise, object: nil)
//                    self.navigationController?.popViewController(animated: true)
                    
                    if (self.param?.rwjlMbs?.filter({$0.rwzt == "3"}) ?? []).count > 0 {
                        let alertC = UIAlertController(title: "检查中有异常，是否去报修？", message: "", preferredStyle: .alert)
                        let cancelAction = UIAlertAction(title: "否", style: .cancel) { action in
                            self.navigationController?.popViewController(animated: true)
                        }
                        let okAction = UIAlertAction(title: "是", style: .default, handler: { action in
                            let vcs = self.navigationController!.viewControllers
                            let parentV = vcs[vcs.count - 2]
                            self.navigationController?.popViewController(animated: false)
                            let vc = OneClickRepairVC(withDeptId: self.deptId, deptName: self.deptName)
                            parentV.navigationController?.pushViewController(vc, animated: true)
                        })
                        alertC.addAction(cancelAction)
                        alertC.addAction(okAction)
                        self.present(alertC, animated: true)
                    } else {
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            }
        } catch {
            print("postJcjdKsjctj error", error)
        }
    }
    
    // MARK: - Setup
    
    func setupUI() {
        taskV.submitBtn.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
        view.addSubview(taskV)
        taskV.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.left.right.equalToSuperview()
        }
    }
}
